﻿#region Copyright and License Notice
// Copyright (C)2010-2016 - Rob Levine and other contributors
// http://configgen.codeplex.com
// 
// This file is part of ConfigGen.
// 
// ConfigGen is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// ConfigGen is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License and 
// the GNU Lesser General Public License along with ConfigGen.  
// If not, see <http://www.gnu.org/licenses/>
#endregion

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using ConfigGen.Utilities;
using ConfigGen.Utilities.Extensions.System.Reflection;
using NUnit.Framework;

namespace ConfigGen.Core.Tests.EndToEndTests
{
    [TestFixture]
    public class RegressionTests
    {
        /// <summary>
        /// Regression test for issue 7 - http://configgen.codeplex.com/workitem/7
        /// "Impossible to generate config without warnings if a token only exists in a switched out region due to an applyWhen"
        /// </summary>
        [Test]
        public void SwitchOutTest()
        {
            using (var testDirectory = new DisposableDirectory())
            {
                string settingsFile = Path.Combine(testDirectory.FullName, "App.Config.Settings.xls");
                Assembly.GetExecutingAssembly().CopyEmbeddedResourceFileTo("TestResources.SwitchedOutTokens.App.Config.Settings.xls", settingsFile);

                string templateFile = Path.Combine(testDirectory.FullName, "App.Config.Template.xml");
                Assembly.GetExecutingAssembly().CopyEmbeddedResourceFileTo("TestResources.SwitchedOutTokens.App.Config.Template.xml", templateFile);

                var settings = new Preferences
                {
                    SettingsFile = settingsFile,
                    TemplateFile = templateFile,
                    OutputDirectory = Path.Combine(testDirectory.FullName, "Configs"),
                };

                var results = TestHelper.ExecuteCfgTest(settings);

                TestHelper.CheckExitResults(results, false);
            }
        }

        /// <summary>
        /// Asserts that if the spreadsheet contains a null token value, and this is used with an applyWhen, no warning
        /// is generated about a missing token.
        /// </summary>
        [Test]
        public void NoWarningsOnNull()
        {
            using (var testDirectory = new DisposableDirectory())
            {
                string settingsFile = Path.Combine(testDirectory.FullName, "App.Config.Settings.xls");
                Assembly.GetExecutingAssembly().CopyEmbeddedResourceFileTo("TestResources.NullToken.App.Config.Settings.xls", settingsFile);

                string templateFile = Path.Combine(testDirectory.FullName, "App.Config.Template.xml");
                Assembly.GetExecutingAssembly().CopyEmbeddedResourceFileTo("TestResources.NullToken.App.Config.Template.xml", templateFile);

                var settings = new Preferences
                {
                    SettingsFile = settingsFile,
                    TemplateFile = templateFile,
                    OutputDirectory = Path.Combine(testDirectory.FullName, "Configs"),
                };

                var results = TestHelper.ExecuteCfgTest(settings);

                TestHelper.CheckExitResults(results, false);

                var generatedConfigFile = new XmlDocument();
                generatedConfigFile.Load(Path.Combine(testDirectory.FullName, "Configs\\DevServer\\App.Config"));
                var appSetting = generatedConfigFile.SelectSingleNode("/configuration/appSettings/add[@key='MyAppSetting']");
                Assert.IsNull(appSetting, "DevServer: App setting should not have been present in output");

                // second file should have appSetting (as token is not null) and is included in the test to make sure the
                // test is functioning correctly (i.e. it is an intentional test mutation).
                generatedConfigFile = new XmlDocument();
                generatedConfigFile.Load(Path.Combine(testDirectory.FullName, "Configs\\ProdServer\\App.Config"));
                appSetting = generatedConfigFile.SelectSingleNode("/configuration/appSettings/add[@key='MyAppSetting']");
                Assert.IsNotNull(appSetting, "ProdServer: App setting should have been present in output");
            }
        }

        /// <summary>
        /// Regression test for issue 15: http://configgen.codeplex.com/workitem/15
        /// "--flat-output does not work with --force-name"
        /// Asserts that if both the forced-filename and machine-suffix options are set, the resulting files have the forced filename
        /// but are also suffixed with the machine name.
        /// </summary>
        [Test]
        public void MachineSuffixWorksWithForcedFilename()
        {
            using (var testDirectory = new DisposableDirectory())
            {
                string settingsFile = Path.Combine(testDirectory.FullName, "App.Config.Settings.xls");
                Assembly.GetExecutingAssembly().CopyEmbeddedResourceFileTo("TestResources.Simple.App.Config.Settings.xls", settingsFile);

                string templateFile = Path.Combine(testDirectory.FullName, "App.Config.Template.xml");
                Assembly.GetExecutingAssembly().CopyEmbeddedResourceFileTo("TestResources.Simple.App.Config.Template.xml", templateFile);

                var settings = new Preferences
                {
                    SettingsFile = settingsFile,
                    TemplateFile = templateFile,
                    OutputDirectory = Path.Combine(testDirectory.FullName, "Configs"),
                    ForcedFilename = "ForcedFilename.xml",
                    FlatDirectoryOutput = true,
                    MachineSuffix = true
                };

                var results = TestHelper.ExecuteCfgTest(settings);

                TestHelper.CheckExitResults(results, false);

                var configDirectory = new DirectoryInfo(settings.OutputDirectory);
                var generatedFiles = configDirectory.GetFiles();
                Assert.AreEqual(3, generatedFiles.Length, "Incorrect number of generated configuration files.");
                Assert.IsNotNull(generatedFiles.FirstOrDefault(f => string.Equals("ForcedFilename.xml.DevServer", f.Name, StringComparison.OrdinalIgnoreCase)), "DevServer file not found");
                Assert.IsNotNull(generatedFiles.FirstOrDefault(f => string.Equals("ForcedFilename.xml.ProdServer", f.Name, StringComparison.OrdinalIgnoreCase)), "ProdServer file not found");
                Assert.IsNotNull(generatedFiles.FirstOrDefault(f => string.Equals("ForcedFilename.xml.Default", f.Name, StringComparison.OrdinalIgnoreCase)), "Default file not found");
            }
        }

        /// <summary>
        /// Regression test for issue 22: http://configgen.codeplex.com/workitem/22
        /// "Token case sensitivity bug issue between template and spreadsheet"
        /// Asserts that if a token has different casing between template and settings file, generation should fail with warnings
        /// for unused token in spreadsheet, unrecognised token in template and no content in generated file. This should be case sensitive.
        /// </summary>
        [Test]
        public void TokenCaseSensitivity()
        {
            using (var testDirectory = new DisposableDirectory())
            {
                // ARRANGE
                string settingsFile = Path.Combine(testDirectory.FullName, "App.Config.Settings.xls");
                Assembly.GetExecutingAssembly().CopyEmbeddedResourceFileTo("TestResources.TokenCaseSensitivity.App.Config.Settings.xls", settingsFile);

                string templateFile = Path.Combine(testDirectory.FullName, "App.Config.Template.xml");
                Assembly.GetExecutingAssembly().CopyEmbeddedResourceFileTo("TestResources.TokenCaseSensitivity.App.Config.Template.xml", templateFile);

                var settings = new Preferences
                {
                    SettingsFile = settingsFile,
                    TemplateFile = templateFile,
                    OutputDirectory = Path.Combine(testDirectory.FullName, "Configs"),
                };

                // ACT
                var results = TestHelper.ExecuteCfgTest(settings);

                // ASSERT
                var firstResult = results.First();

                Assert.IsTrue(firstResult.HasWarnings, "Warnings were expected due to case sensitivity issues");
               
                Assert.AreEqual(0, firstResult.TokenUseCounts["environment"], "environment setting from spreadsheet should have zeero uses");
                Assert.IsTrue(firstResult.UnrecognisedTokenCounts.ContainsKey("ENVIRONMENT"), "ENVIRONMENT token in template should be in unrecognised list");
                Assert.AreEqual(1, firstResult.UnrecognisedTokenCounts["ENVIRONMENT"], "Incorrect unrecognised count for ENVIRONMENT");
                var generatedConfigFile = new XmlDocument();
                generatedConfigFile.Load(Path.Combine(testDirectory.FullName, "Configs\\DevServer\\App.Config"));
                var environment = generatedConfigFile.SelectSingleNode("/configuration/Environment/text()");
                Assert.IsNull(environment, "environment: should be null");
            }
        }

        [Test]
        public void ReadOnlySettingsFileCausesError()
        {
            using (var testDirectory = new DisposableDirectory())
            {
                string settingsFile = Path.Combine(testDirectory.FullName, "App.Config.Settings.xls");
                Assembly.GetExecutingAssembly().CopyEmbeddedResourceFileTo("TestResources.Simple.App.Config.Settings.xls", settingsFile);

                var settingsFileInfo = new FileInfo(settingsFile);
                settingsFileInfo.Attributes |= FileAttributes.ReadOnly;

                string templateFile = Path.Combine(testDirectory.FullName, "App.Config.Template.xml");
                Assembly.GetExecutingAssembly().CopyEmbeddedResourceFileTo("TestResources.Simple.App.Config.Template.xml", templateFile);

                var settings = new Preferences
                {
                    SettingsFile = settingsFile,
                    TemplateFile = templateFile,
                    OutputDirectory = Path.Combine(testDirectory.FullName, "Configs"),
                    ForcedFilename = "ForcedFilename.xml",
                    FlatDirectoryOutput = true,
                    MachineSuffix = true
                };

                var results = TestHelper.ExecuteCfgTest(settings);

                TestHelper.CheckExitResults(results, false);
            }
        }
    }
}
